import React, { useRef, useState } from "react";
import { Form, FormItem, FormHelpers, Input, Button } from "@hi-ui/hiui";
import { UserFilled, LockFilled } from "@hi-ui/icons";
import { getLogins } from "src/api";
import { setCookie } from "src/util/cookie";
import { useNavigate } from "react-router-dom";
import "./index.scss";
const prefix = "login";
interface LoginFiled {
  userName: string;
  password: string;
}
const Login = () => {
  const navigate = useNavigate();
  const [formData, setFormData] = useState<LoginFiled>({
    userName: "",
    password: "",
  });
  const refForm = useRef<FormHelpers>(null);
  const handleSubmit = async () => {
    const res = await refForm.current?.validate();
    if (res) {
      const response = await getLogins(formData);
      const { success, data } = response.data;
      if (success) {
        setCookie(data.token);
        navigate("/");
      }
    }
  };
  return (
    <div className={prefix}>
      <div className={`${prefix}-main`}>
        <div className={`${prefix}-title`}>登录</div>
        <Form
          className="mt-5"
          initialValues={formData}
          placement="horizontal"
          labelWidth={110}
          innerRef={refForm}
        >
          <FormItem
            label="用户名称"
            required
            field={"userName"}
            validateTrigger={["onChange", "onBlur"]}
            valueType="string"
            rules={[{ required: true, message: "请输入用户名称" }]}
          >
            <Input
              value={formData.userName}
              onChange={(e) => {
                setFormData({ ...formData, userName: e.target.value });
              }}
              prefix={<UserFilled />}
              clearable
              style={{ width: "300px" }}
              placeholder="请输入用户名称"
            ></Input>
          </FormItem>
          <FormItem
            label="密码"
            required
            field={"password"}
            valueType="string"
            validateTrigger={["onBlur", "onChange"]}
            rules={[{ required: true, message: "请输入登录密码" }]}
          >
            <Input
              value={formData.password}
              onChange={(e) => {
                setFormData({ ...formData, password: e.target.value });
              }}
              prefix={<LockFilled />}
              clearable
              type="password"
              style={{ width: "300px" }}
              placeholder="请输入密码"
            ></Input>
          </FormItem>
        </Form>
        <div className={`${prefix}-btn flex flex-row justify-center`}>
          <Button type="primary">注册</Button>
          <Button type="primary" onClick={handleSubmit}>
            登录
          </Button>
        </div>
      </div>
    </div>
  );
};
export default Login;
